<template>
  <div class="ele-body">
    <!-- 搜索表单 -->
    <div class="block-interval">
      <a-card :bordered="false">
        <a-form layout="inline" :model="where" @keydown.enter.prevent="reload">
          <a-row style="width: 100%">
            <a-col :span="21">
              <a-form-item label="">
                代理商名称:
                <a-input style="width: 160px;margin-right: 10px;" v-model:value.trim="where.name"
                         placeholder="请输入名称" allow-clear />
                所在地域:
                <a-select v-model:value="where.region" placeholder="请选择" style="width: 160px;margin-right: 10px;">
                  <a-select-option v-for="region in regionList" :key="region" :value="region">
                    {{ region }}
                  </a-select-option>
                </a-select>
                级别:
                <a-select v-model:value="where.level" placeholder="请选择" style="width: 160px;margin-right: 10px;">
                  <a-select-option value="金牌代理商">金牌代理商</a-select-option>
                  <a-select-option value="银牌代理商">银牌代理商</a-select-option>
                  <a-select-option value="铜牌代理商">铜牌代理商</a-select-option>
                </a-select>
                <a-space>
                  <a-button type="primary" @click="reload">查询</a-button>
                  <a-button @click="reset">重置</a-button>
                </a-space>
              </a-form-item>
            </a-col>

            <!--导出excel-->
            <a-col :span="3">
              <a-form-item class="ele-text-center">
                <a-space>
                  <a-button @click="exportExcel" type="primary" :size="size"
                            style="background-color: rgb(254,108,17);border:rgb(254,108,17);">
                    <template #icon>
                      <DownloadOutlined />
                    </template>
                    按条件导出
                  </a-button>
                </a-space>
              </a-form-item>
            </a-col>

          </a-row>

        </a-form>
      </a-card>
    </div>

    <!-- 表格 -->
    <div>
      <a-card :bordered="false">
        <ele-pro-table
          ref="table"
          row-key="id"
          :datasource="url"
          :columns="columns"
          :where="where"
          :scroll="{ x: 'max-content' }"
        >
          <!-- table上边工具栏 -->
          <template #toolbar>
            <a-space>
              <a-button v-if="user.roleId !== '2'"
                        type="primary" @click="openEdit()">
                <template #icon>
                  <plus-outlined />
                </template>
                <span>新建代理商</span>
              </a-button>
              <!--              <a-button type="danger" @click="removeBatch()">
                              <template #icon>
                                <delete-outlined />
                              </template>
                              <span>删除</span>
                            </a-button>-->
            </a-space>
          </template>

          <!-- table列表状态栏 -->
          <!-- 1是激活，2是禁用 -->
          <template #state="{ record }">
            <a-switch :checked="record.statusFlag === 1" @change="checked => editState(checked, record)" />
          </template>

          <!-- table操作栏按钮 -->
          <template #action="{ record }">
            <a-space>
              <a @click="openEdit(record)" v-if="user.roleId !== '2'">修改</a>
              <a @click="openEdit(record)" v-if="user.roleId === '2'">详情</a>
              <a-divider type="vertical" />
              <a-popconfirm title="确定要删除此代理商吗？" @confirm="remove(record)" v-if="user.roleId !== '2'">
                <a class="ele-text-danger">删除</a>
              </a-popconfirm>
            </a-space>
          </template>

          <template #image="{ record }">
            <a-avatar :size="60" shape="square" :src="record.logoUrl" />
          </template>

          <template #level="{ record }">
            <ele-tag v-if="record.level === '金牌代理商'" size="mini" color="yellow">{{ record.level }}</ele-tag>
            <ele-tag v-if="record.level === '银牌代理商'" size="mini">{{ record.level }}</ele-tag>
            <ele-tag v-if="record.level === '铜牌代理商'" size="mini" color="orange">{{ record.level }}</ele-tag>
          </template>
          <template #contact="{ record }">
            <span style="display: block;">姓名：{{ record.contactName }}</span>
            <span style="display: block;">电话：{{ record.contactPhone }}</span>
            <span style="display: block;">邮箱：{{ record.contactMail }}</span>
          </template>

          <template #expirationDate="{ record }">
            <span style="display: block;">开始：{{ record.expirationDateStart }}</span>
            <span style="display: block;">结束：{{ record.expirationDateEnd }}</span>
          </template>
        </ele-pro-table>


      </a-card>
    </div>
  </div>

  <!-- 编辑弹窗 -->
  <position-edit v-model:visible="showEdit" :data="current" @done="reload" />
</template>

<script>
import { createVNode } from 'vue';
// 删除，感叹号，加号图标
import { ExclamationCircleOutlined, PlusOutlined } from '@ant-design/icons-vue';
import PositionEdit from './info-edit.vue';
import { AgentApi } from '@/api/AgentApi';
import { utils, writeFile } from 'xlsx';
import { DashboardApi } from '@/api/DashboardApi';

export default {
  name: 'region',
  components: {
    PlusOutlined,
    PositionEdit
  },
  data() {
    return {
      // 地域信息
      regionList:[],
      // 用户信息
      user: {},
      // 表格数据接口
      url: '/business/api/agent/findPage',
      // 表格列配置
      columns: [
        {
          title: '序号',
          key: 'index',
          width: 48,
          customRender: ({ index }) => this.$refs.table.tableIndex + index
        },
        {
          title: '代理商名称',
          dataIndex: 'name',
          width: 160
        },
        {
          title: 'logo',
          width: 100,
          slots: { customRender: 'image' },
          align: 'center' // 添加这一行来使内容居中对齐
        },
        {
          title: '所在地域',
          dataIndex: 'region',
          width: 80,
          align: 'center' // 添加这一行来使内容居中对齐
        },
        {
          title: '级别',
          dataIndex: 'level',
          width: 120,
          slots: { customRender: 'level' },
          align: 'center' // 添加这一行来使内容居中对齐
        },
        {
          title: '联系人信息',
          width: 280,
          slots: { customRender: 'contact' }
        },
        {
          title: '代理商有效期',
          width: 150,
          sorter: false,
          slots: { customRender: 'expirationDate' }
        },
        /*{
          title: '更新时间',
          dataIndex: 'updateTime',
          sorter: true,
          width: 180
        },*/
        {
          title: '状态',
          dataIndex: 'statusFlag',
          align: 'center',
          width: 120,
          slots: { customRender: 'state' }
        },
        {
          title: '操作',
          key: 'action',
          width: 150,
          align: 'center',
          fixed: 'right',
          slots: { customRender: 'action' }
        }
      ],
      // 表格搜索条件
      where: {},
      // 表格选中数据
      selection: [],
      // 当前编辑数据
      current: null,
      // 是否显示编辑弹窗
      showEdit: false,
    };
  },
  mounted() {
    this.getUser();
    this.fetchRegionList();
  },
  methods: {
    // 获取地域信息
    async fetchRegionList() {
      const res = await AgentApi.findRegionList({});
      this.regionList = res.data;
    },
    // 获取用户信息
    async getUser() {
      const res = await DashboardApi.getUser();
      this.user = res.data;
    },
    /**
     * 搜索按钮
     */
    reload() {
      this.selection = [];
      this.$refs.table.reload({ page: 1 });
    },

    /**
     * 重置搜索
     */
    reset() {
      this.where = {};
      this.$nextTick(() => {
        this.reload();
      });
    },

    /**
     * 删除单个
     */
    async remove(row) {
      const result = await AgentApi.del({ id: row.id });
      this.$message.success(result.message);
      this.reload();
    },

    /**
     * 批量删除
     */
    removeBatch() {
      if (!this.selection.length) {
        this.$message.error('请至少选择一条数据');
        return;
      }
      this.$confirm({
        title: '提示',
        content: '确定要删除选中的代理商吗?',
        icon: createVNode(ExclamationCircleOutlined),
        maskClosable: true,
        onOk: async () => {
          let params = this.selection.map(d => d.id);
          const result = await AgentApi.batchDel(params);
          this.$message.success(result.message);
          this.reload();
        }
      });
    },

    /**
     * 打开编辑弹窗
     */
    openEdit(row) {
      this.current = row;
      this.showEdit = true;
    },

    /**
     * 修改产品状态
     */
    async editState(checked, row) {
      if (this.user.roleId && this.user.roleId === '2') {
        return;
      }
      const id = row.id;
      // 职位状态：1-启用，2-禁用
      const statusFlag = checked ? 1 : 2;
      const result = await AgentApi.edit({ id, statusFlag });
      this.$message.success(result.message);
      row.statusFlag = statusFlag;
    },
    exportExcel() {
      this.loading = true;
      const exportWhere = {
        ...this.where,
        pageNo: 1,
        pageSize: 10000
      };

      AgentApi.findPage(exportWhere).then((res) => {
        let data = res.data.rows;
        let array = [
          [
            '代理商名称',
            '所在地域',
            '级别',
            '联系人姓名',
            '联系人电话',
            '联系人邮箱',
            '代理商有效期开始',
            '代理商有效期结束',
            '操作时间',
            '状态'
          ]
        ];
        data.forEach((d) => {
          if (d.statusFlag === 1) {
            d.statusFlag = '启用';
          } else {
            d.statusFlag = '禁用';
          }
          array.push([
            d.name,
            d.region,
            d.level,
            d.contactName,
            d.contactPhone,
            d.contactMail,
            d.expirationDateStart,
            d.expirationDateEnd,
            d.updateTime,
            d.statusFlag
          ]);
        });
        writeFile(
          {
            SheetNames: ['代理商信息'],
            Sheets: {
              代理商信息: utils.aoa_to_sheet(array)
            }
          },
          '代理商信息.xlsx'
        );
        this.loading = false;
      }).catch(e => {
        this.loading = false;
        this.$message.error(e.message);
      });
    }
  }
};
</script>

<style scoped>
/*搜索框与表格之间的间隙*/
.block-interval {
  margin-bottom: 10px;
}

/*重写顶部搜索表单的样式*/
.ant-form-item {
  margin-bottom: 0;
}
/* 表格斑马样式 **/
/deep/.ant-table-tbody tr:nth-child(2n)
{
  background-color:#fafafa;
}
</style>
